package com.wzw.shortcuthelper.core.helper

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.text.TextUtils
import android.util.Log
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.util.*


class PermissionRequest(private val mSource: Context) {
    /**
     * Start.
     */
    fun start() {
        var intent: Intent
        intent = when {
            MARK.contains("huawei") -> {
                huaweiApi(mSource)
            }
            MARK.contains("honor", true) -> {
                huaweiApi(mSource)
            }
            MARK.contains("xiaomi") -> {
                xiaomiApi(mSource)
            }
            MARK.contains("oppo") -> {
                oppoApi(mSource)
            }
            MARK.contains("vivo") -> {
                vivoApi(mSource)
            }
            MARK.contains("meizu") -> {
                meizuApi(mSource)
            }

            MARK.contains("360") -> {
                Api360(mSource)
            }
            MARK.contains("nubia") -> {
                nubiaApi(mSource)
            }
            else -> {
                defaultApi(mSource)
            }
        }

        try {
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            mSource.startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace()
            intent = defaultApi(mSource)
            mSource.startActivity(intent)
        }
        if (MARK.contains("vivo")) {
            mSource.getSharedPreferences("temp", Context.MODE_PRIVATE).apply {
                edit().putBoolean("vivo", true).apply()
            }

        }
    }

    companion object {
        private const val MIUI_VERSION_NAME = "ro.miui.ui.version.name"
        private val MARK = Build.MANUFACTURER.toLowerCase(Locale.ROOT)
        private fun defaultApi(context: Context): Intent {
            val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
            intent.data = Uri.fromParts("package", context.packageName, null)
            return intent
        }


    }

    private fun huaweiApi(context: Context): Intent {
        val intent = Intent()
        intent.component =
            ComponentName(
                "com.huawei.systemmanager",
                "com.huawei.permissionmanager.ui.MainActivity"
            )
        if (hasActivity(context, intent)) {
            return intent
        }

        intent.component = ComponentName(
            "com.hihonor.systemmanager",
            "com.huawei.securitycenter.permission.ui.activity.MainActivity"
        )
        if (hasActivity(context, intent)) {
            return intent
        }
        return intent
    }

    private fun xiaomiApi(context: Context): Intent {
        val version = getSystemProperty(MIUI_VERSION_NAME)
        if (TextUtils.isEmpty(version)) {
            return defaultApi(context)
        }
        val versionI: Int
        versionI = try {
            version.substring(1).toInt()
        } catch (e: NumberFormatException) {
            e.printStackTrace()
            return defaultApi(context)
        }
        //xiaomi note2 MIUI 9.5进行适配，需要跳转至小米自带的权限软件
        //xiaomi note2 MUUI 10.0进行适配，需要跳转至小米自带的权限软件
        if (versionI >= 9) {
            val intent = Intent("miui.intent.action.APP_PERM_EDITOR")
            intent.component = ComponentName(
                "com.miui.securitycenter",
                "com.miui.permcenter.permissions.PermissionsEditorActivity"
            )
            intent.putExtra("extra_pkgname", context.packageName)
            return intent
        }
        if (versionI >= 7) {
            val intent = Intent("miui.intent.action.APP_PERM_EDITOR")
            intent.putExtra("extra_pkgname", context.packageName)
            return intent
        }
        return defaultApi(context)
    }

    /* access modifiers changed from: private */ /* access modifiers changed from: public */
    private fun vivoApi(context: Context): Intent {
        try {
            val intent = Intent()
            intent.putExtra("packagename", context.packageName)

            intent.component = ComponentName(
                "com.bbk.launcher2",
                "com.bbk.launcher2.installshortcut.PurviewActivity"
            )

            if (hasActivity(context, intent)) {
                return intent
            }

            intent.component = ComponentName(
                "com.vivo.permissionmanager",
                "com.vivo.permissionmanager.activity.SoftPermissionDetailActivity"
            )
            if (hasActivity(context, intent)) {
                return intent
            }
            intent.component = ComponentName(
                "com.iqoo.secure",
                "com.iqoo.secure.safeguard.SoftPermissionDetailActivity"
            )
            if (hasActivity(context, intent)) {
                return intent
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return defaultApi(context)
    }


    private fun isPermissionManagerAppExisted(context: Context): Boolean {
        var applicationInfo: ApplicationInfo? = null
        try {
            applicationInfo = context.packageManager
                .getApplicationInfo("com.vivo.permissionmanager", 0)
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
            return false

        }
        return applicationInfo != null
    }


    fun oppoApi(context: Context): Intent {
        val intent = Intent()

        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        intent.putExtra("packageName", context.packageName)
        //OPPO R9S 6.0.1,由于OPPO手机在"应用列表-xx应用-权限"下的权限列表并没有创建快捷方式一项，只能到"权限隐私-创建快捷方式"中设置。
        intent.setClassName(
            "com.oppo.launcher",
            "com.oppo.launcher.shortcut.ShortcutSettingsActivity"
        )
        if (hasActivity(context, intent)) return intent
        intent.component = ComponentName(
            "com.color.safecenter",
            "com.color.safecenter.permission.PermissionManagerActivity"
        )

        if (hasActivity(context, intent)) return intent

        return intent
    }

    private fun meizuApi(context: Context): Intent {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return defaultApi(context)
        }
        val intent = Intent("com.meizu.safe.security.SHOW_APPSEC")
        intent.putExtra("packageName", context.packageName)
        intent.component =
            ComponentName("com.meizu.safe", "com.meizu.safe.security.AppSecActivity")
        return intent
    }

    private fun nubiaApi(context: Context): Intent {
        val intent = Intent()
        intent.putExtra("packagename", context.packageName)

        intent.component = ComponentName(
            "com.android.packageinstaller", "com.android.packageinstaller.permission.ui.ManagePermissionsActivity"
        )

        if (hasActivity(context, intent)) {
            return intent
        }
        return defaultApi(context)
    }

    private fun Api360(context: Context): Intent {
        val intent = Intent()
        intent.putExtra("packagename", context.packageName)

        intent.component = ComponentName(
            "com.qiku.android.launcher3", "com.qiku.android.launcher3.LauncherSettingsActivity"
        )

        if (hasActivity(context, intent)) {
            return intent
        }
        return defaultApi(context)
    }

    private fun hasActivity(context: Context, intent: Intent): Boolean {
        val packageManager = context.packageManager
        return packageManager.queryIntentActivities(
            intent,
            PackageManager.MATCH_DEFAULT_ONLY
        ).size > 0
    }

    fun getSystemProperty(propName: String): String {
        var input: BufferedReader? = null
        return try {
            val p = Runtime.getRuntime().exec("getprop $propName")
            input = BufferedReader(InputStreamReader(p.inputStream), 1024)
            input.readLine()
        } catch (ex: IOException) {
            ""
        } finally {
            if (input != null) {
                try {
                    input.close()
                } catch (ignored: IOException) {
                }
            }
        }
    }
}